import { reactive } from 'vue';

// Define notification types enum
export enum NotificationType {
	MESSAGES = 'messages',
	UPDATES = 'updates',
	ALERTS = 'alerts',
	SWITCHTABLE = 'SWITCHTABLE',
}

// Interface for shared state
interface NotificationShared {
	notifications : { [key in NotificationType]: Function[] }; // 只使用 Function[] 类型
}

// Initialize shared state
const shared = reactive<NotificationShared>({
	notifications: {
		[NotificationType.MESSAGES]: [],
		[NotificationType.UPDATES]: [],
		[NotificationType.ALERTS]: [],
		[NotificationType.SWITCHTABLE]: [],
	},
});

// Method to send a notification
function sendNotification(type : NotificationType, count : number = 1) {
	// Trigger the listeners if they are available
	if (Array.isArray(shared.notifications[type])) {
		shared.notifications[type].forEach(callback => {
			callback(count);  // Send the count (or other relevant data)
		});
	}
}

// Register a listener for a specific notification type
function listener(type : NotificationType, callback : Function) {
	// Initialize the array if it's not already an array
	if (!Array.isArray(shared.notifications[type])) {
		shared.notifications[type] = [];
	}

	shared.notifications[type].push(callback);
}

// Clear notifications for a specific type
function clearNotification(type : NotificationType) {
	shared.notifications[type] = [];
}

// Clear all notifications
function clearAllNotifications() {
	Object.keys(shared.notifications).forEach((key) => {
		shared.notifications[key as NotificationType] = [];
	});
}

// Export composable API
export function NotificationManager() {
	return {
		shared,
		sendNotification,
		listener,
		clearNotification,
		clearAllNotifications,
	};
}